<template>
    <div class="map-container">
        <div id="map" class="gis-map"></div>
        <div class="tool">
            <a-select show-search :filter-option="filterOption" option-filter-prop="children" style="width: 200px;margin-right: 20px" allowClear v-model="searchCity" placeholder="请选择城市">
                <a-select-option v-for="item in cityList" :key="item.value" :value="item.label">{{ item.label }}</a-select-option>
            </a-select>
            <a-input-search v-model="searchName" placeholder="请输入搜索内容" style="width: 200px;margin-right: 20px" @search="searchLocationName"></a-input-search>
        </div>
    </div>
</template>
<script>
import axios from "axios";
import areaJson from "@/utils/area";
export default {
    props:['center','mapLayer','disabled'],
    name: "gisMap",
    data() {
        return {
            map:null,
            update:true,
            marker:null,
            searchCity:'北京市',
            cityList:[],
            searchName:'',
            selectedLocation:undefined,
            searchList:[],
        }
    },
    watch: {
        center() {
            this.initLeaftMap()
        }
    },
    mounted() {
        this.cityList = areaJson
        setTimeout(()=>{
            console.log('地图初始化完成，中心点：',this.center)
            this.initLeaftMap()
        },500)
    },
    methods:{
        filterOption(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        initLeaftMap() {
            if (this.map) this.map.remove();
            this.map = null;
            //限制地图的拖动范围是正负90到正负180，这样才合理。
            var corner1 = L.latLng(-90, -180); //设置左上角经纬度
            var corner2 = L.latLng(90, 180);	//设置右下点经纬度
            var bounds = L.latLngBounds(corner1, corner2); //构建视图限制范
            //自定义leaflet天地图经纬度坐标
            //设置地图相关初始配置
            this.map = L.map("map", {
                center:this.center,
                minZoom:2,
                maxZoom: 17,
                preferCanvas:true,
                zoom: 10, //初始地图缩放级别
                crs: L.CRS.EPSG4326,//设置坐标系4326
                scrollWheelZoom: true, //默认开启鼠标滚轮缩放
                zoomControl: false, //禁用 + - 按钮
                doubleClickZoom: false, // 禁用双击放大
                attributionControl: false, // 移除右下角leaflet标识
                maxBounds: bounds,
            });
            const TK_KEY = "5c68d0d10d0fa048192d148108ba00b9";


            // 底图
            //vec_c 交通标记
            const vec_c = 'http://{s}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk='
            //cta_c 地名地点标记
            const cta_c = 'http://{s}.tianditu.com/cta_c/wmts?layer=cta&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
            //img_c 卫星地图
            const img_c = 'http://{s}.tianditu.com/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
            if(this.mapLayer){
                L.tileLayer(vec_c + TK_KEY, {
                    maxZoom: 18,
                    tileSize: 256,
                    zoomOffset: 1,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                }, { noWrap: false }).addTo(this.map);
                L.tileLayer(cta_c + TK_KEY, {
                    maxZoom: 18,
                    tileSize: 256,
                    zoomOffset: 1,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                }, { noWrap: false }).addTo(this.map);
            }else{
                L.tileLayer(img_c + TK_KEY, {
                    maxZoom: 18,
                    tileSize: 256,
                    zoomOffset: 1,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                }, { noWrap: false }).addTo(this.map);
                L.tileLayer(cta_c + TK_KEY, {
                    maxZoom: 18,
                    tileSize: 256,
                    zoomOffset: 1,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                }, { noWrap: false }).addTo(this.map);
            }

            //如果有中心点，也就是marker坐标直接添加maker到地图
            if(this.center.length){
                this.marker = L.marker(this.center, {
                    draggable: true,
                    icon: L.icon({
                        iconUrl: require('@/assets/img/logo-ico.png'),
                        iconSize: [30, 30],
                        iconAnchor: [15, 30],
                        popupAnchor: [0, -30]
                    })
                }).addTo(this.map);
                this.marker.bindPopup(`经度：${this.center[0]}<br>纬度：${this.center[1]}`).openPopup();
            }
            if(this.disabled){
                return
            }
            // 监听点击事件
            this.map.on('click', this.onMapClick);


        },
        onMapClick(e) {
            // 移除旧的标记
            if (this.marker) {
                this.map.removeLayer(this.marker);
            }

            // 创建新标记
            this.marker = L.marker([e.latlng.lat, e.latlng.lng], {
                draggable: true,
                icon: L.icon({
                    iconUrl: require('@/assets/img/logo-ico.png'),
                    iconSize: [30, 30],
                    iconAnchor: [15, 30],
                    popupAnchor: [0, -30]
                })
            }).addTo(this.map);
            this.marker.bindPopup(`经度：${e.latlng.lng}<br>纬度：${e.latlng.lat}`).openPopup();
            this.$emit('markerLngLat', [e.latlng.lng,e.latlng.lat])
        },
        async searchLocationName() {
            if(!this.searchCity){
                this.$message.error('请选择城市')
                return
            }
            let params = {
                postStr: {
                    keyWord: this.searchName,
                    queryType: '12',
                    start: '0',
                    count: '10',
                    specify: this.searchCity,
                },
                type: 'query',
                tk: '5c68d0d10d0fa048192d148108ba00b9'
            }
            params.postStr = JSON.stringify(params.postStr)
            const res = await axios.get('https://api.tianditu.gov.cn/v2/search', {
                params: params,
            })
            if(res.status == 200){
                let data = res.data
                if(data.pois){
                    this.searchList = data.pois
                    this.moveTo()
                }else{
                    this.$message.error('暂无搜索结果')
                }
            }

        },
        //移动到搜索的位置
        moveTo() {
            if(this.searchList.length > 0){
                let location = this.searchList[0].lonlat.split(',')
                let lat = location[1]*1
                let lng = location[0]*1
                console.log(location)
                this.map.setView([lat, lng],13)
            }
        }
    },
}
</script>
<style scoped lang="scss">
.map-container{
    width: 100%;
    height: 100%;
    .gis-map{
        position: relative;
        width: 100%;
        height: 100%;
    }
}
.tool{
    z-index: 1000;
    position: absolute;
    right: 20px;
    top: 20px;
}
</style>
